package com.hrt.datasender.datasent.service.handler;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.btcode.log.ILog;
import com.hrt.datasender.datasent.DataSender;
import com.hrt.datasender.datasent.socket.SocketClient;
import com.hrt.datasender.mq.MqKit;
import com.hrt.datasender.mq.model.PacketModel;

/**
 * 处理完整的报文
 *
 * @author gislin
 */
public class MessageReceiveProcess extends SimpleChannelUpstreamHandler {

    private ILog log;

    private SocketClient client;

    public MessageReceiveProcess(SocketClient client) {
        this.client = client;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent msgEvent) throws Exception {
        super.messageReceived(ctx, msgEvent);
        log = DataSender.log;
        String msg = msgEvent.getMessage().toString().trim();
        log.info("收到报文(" + msgEvent.getChannel().getRemoteAddress() + ")：" + msg);
        client.updateLastHeartBreakTime();

        PacketModel packetModel = new PacketModel();
        packetModel.setMsg(msg);
        packetModel.setIp(client.getIp());
        packetModel.setPort(String.valueOf(client.getPort()));
        MqKit.productMsgToCenterStationMQ(packetModel);
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent msgEvent) throws Exception {
        super.channelConnected(ctx, msgEvent);
        System.out.println("连接打开。");
    }
}